const {
	Controller
} = require('dx-router-admin')
module.exports = class Index extends Controller {

	constructor(ctx) {
		super(ctx)

	}	
	//列表
	async photo() {
		let lastId = this.$dx.request.param('lastId');
		let res = await this.$dx.service.photos.where(this.$dx.request.param('where')).field('title,path,color,cuIcon,label').paginate(lastId,10,0);		
		this.echoJson('获取成功', res);
	}
	//详情
	async index(){
		let id = this.$dx.request.param('id');
		let pid = this.$dx.request.param('pid');
		if(!id && !pid){
			this.error('相册参数错误');
		}
		let row = await this.$dx.service.userphoto.where('_id',pid).field('title,images,bg_music,user_id').find(0);		
		if(this.$dx.tool.is_empty(row)){
			if(!id){
				this.error('记录未找到');
			}
			row = await this.$dx.service.photos.where('_id',id).field('title,images,bg_music,len,num').find(0);
		}
		this.echoJson('获取成功',row);
	}
	//创建
	async create(){
		const title = this.$dx.request.post('title');
		const images = this.$dx.request.post('images');
		const bg_music = this.$dx.request.post('bg_music');
		const id = this.$dx.request.post('id');		
		let row = await this.$dx.service.photos.where('_id',id).find();			
		if(!row.hasData()){
			this.error('记录未找到');
		}		
		if(row.len==1 && images.length != row.num){
			this.error('图片未上传完整');
		}
		if(row.len>1){
			if(images.length!=row.len){
				this.error('请上传完整图片');
			}
			for(let i=0;i<row.len;i++){
				if(images[i].length != row.num){
					this.error('图片数量不对');
				}
			}
		}
		const res = await this.$dx.service.userphoto.insert({
			user_id:this.$dx.auth.uid,
			images:images,
			path:row.path,
			photo_id:id,
			bg_music,
			status:0,
			title
		});
		this.echoJson('提交成功',res);
	}
	//添加
	async add_img() {
		let data = this.$dx.request.post();
		let schema = this.Joi.object({
			file_size: this.Joi.number().required().error(new Error('文件大小不能为空')),
			type: this.Joi.string().required().error(new Error('文件类型不能为空')),
			file_name: this.Joi.string().required().error(new Error('文件名称不能为空')),
			url: this.Joi.string().required().error(new Error('文件url不能为空')),
		})
		const {
			error
		} = schema.validate(data, {
			// false：表示对所有字段进行校验错误；如果不定义，只要发现不合法的字段就会停止校验
			abortEarly: this.abortEarly,
			// 允许验证被对象包含没有定义校验规则的未知字段，否则会认为被校验数据不通过
			allowUnknown: this.allowUnknown
		})
		if (error) {
			this.error(error.message);
		}
		data.user_id = this.$dx.auth.uid;
		let {
			id
		} = await this.$dx.service.resource.field(true).insert(data);
		if (id) {
			this.echoJson('添加成功', id);
		}
		this.error('添加失败');
	}
}